package com.mobile.persistent.dao;

import java.util.HashMap;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.google.common.collect.Maps;
import com.mobile.common.base.support.Page;
import com.mobile.persistent.base.BaseDao;
import com.mobile.persistent.entity.Users;

@Repository
@SuppressWarnings("unchecked")
public class UserDao extends BaseDao<Users, Long> {

	public Page<Users> findPageByCriteria(Users user, int pageNo,int pageSize){
		Criteria criteria = createCriteria();
		//TODO 添加user的查询参数
		if(user!=null&&user.getUserName()!=null){
			criteria.add(Restrictions.ilike("userName", user.getUserName(),MatchMode.ANYWHERE));
		}
		//criteria.addOrder(Order.desc("id"));
		return findPageByCriteria(criteria, pageNo, pageSize);
	}
	
	public Page<Users> findPageByHql(Users user, int pageNo,int pageSize){
		Page<Users> page = new Page<Users>();
		String hql = "from Users where lastIp=:ip";
		Map<String,Object> params = new HashMap<String, Object>();
		//TODO 填充参数
		Query query = createQuery(hql, params);
		query.setFirstResult((pageNo-1)*pageSize);
		query.setMaxResults(pageSize);
		page.setResult(query.list());
		return page;
	}
	
	// 根据用户名和密码获取用户信息
	public Users findByNamePwd(String userName, String userPwd){
		String hql = "from Users where userName=:userName and passWord=:userPwd";
		Map<String,Object> params = Maps.newHashMap();
		params.put("userName", userName);
		params.put("userPwd", userPwd);
		return createQuery(hql, params).list().isEmpty()?null:(Users)createQuery(hql, params).list().get(0);
	}
}
